<template>
  <div class="login-container">

    <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
      <div class="login-headimg"></div>
      <el-form-item prop="mobile">
        <el-input v-model="loginForm.mobile"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="loginForm.code"></el-input>
      </el-form-item>
      <el-form-item prop="agree">
        <el-checkbox v-model="loginForm.agree">我已阅读并同意用户协议和隐私条款</el-checkbox>
      </el-form-item>
      <el-button type="primary" @click="loginBtn" :loading="isloading">登陆</el-button>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/api/user.js'
export default {
  data() {
    return {
      isloading: false,
      loginForm: {
        mobile: '13911111111',
        code: '246810',
        agree: false
      },
      loginFormRules: {
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的号码格式', trigger: 'change' }
        ],
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '请输入正确的验证码格式' }
        ],
        agree: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback()
              } else {
                callback(new Error('请同意用户协议'))
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    async loginBtn() {
      this.isloading = true
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return (this.isloading = false)
        login(this.loginForm)
          .then(res => {
            this.$message.success('登陆成功')
            this.isloading = false
            this.$router.push('/home')
            window.sessionStorage.setItem('user', JSON.stringify(res.data.data))
          })
          .catch(() => {
            this.$message.error('登陆失败，用户名或密码错误')
            this.isloading = false
          })
      })
    }
  }
}
</script>

<style  scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: url('./login_bg.jpg') no-repeat;
  background-size: cover;
}
.el-form {
  min-width: 300px;
  padding: 50px;
  background-color: #fff;
}
.login-headimg {
  background: url('./logo_index.png') no-repeat;
  background-size: 148px auto;
  width: 150px;
  margin: -20px auto 20px;
  height: 33px;
}
.el-button {
  width: 100%;
}
</style>
